package com.hanxiaozhang.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2022/9/8
 * @since 1.0.0
 */
@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    public <T> void set(String key, T value) {
        String json = JSONObject.toJSONString(value);
        set(key, json);
    }

    public <T> void set(String key, T value, int timeout, TimeUnit timeUnit) {
        String json = JSONObject.toJSONString(value);
        set(key, json, timeout, timeUnit);
    }

    public void set(String key, String value, int timeout, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }


    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }


    public <T> T get(String key, Class<T> clazz) {
        String json = get(key);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return JSONObject.parseObject(json, clazz);
    }


    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }

    public void deletes(List<String> keys) {
        stringRedisTemplate.delete(keys);
    }

    public Long incr(String key, Long num) {
        return stringRedisTemplate.opsForValue().increment(key, num);
    }

    public void expire(String key, Long timeout) {
        stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }


}
